import pyaudio
import wave


def record_and_save(
    duration=10,
    filename="output.wav",
    chunk=1024,
    audio_format=pyaudio.paInt16,
    channels=1,
    rate=16000,
):
    """
 

    参数:
    duration (int): 录音时长，单位秒，默认10秒。
    filename (str): 输出文件名，默认"output.wav"。
    chunk (int): 每次读取的音频块大小，默认1024。
    audio_format (int): 音频格式，默认pyaudio.paInt16。
    channels (int): 声道数，默认1。
    rate (int): 采样率，默认16000 Hz。
    """
    try:
        p = pyaudio.PyAudio()
        stream = p.open(
            format=audio_format,
            channels=channels,
            rate=rate,
            input=True,
            frames_per_buffer=chunk,
        )

        print("开始录音...")
        frames = []

        for _ in range(0, int(rate / chunk * duration)):
            data = stream.read(chunk)
            frames.append(data)

        print("录音结束...")

        stream.stop_stream()
        stream.close()
        p.terminate()

        wf = wave.open(filename, "wb")
        wf.setnchannels(channels)
        wf.setsampwidth(p.get_sample_size(audio_format))
        wf.setframerate(rate)
        wf.writeframes(b"".join(frames))
        wf.close()

    except Exception as e:
        print(f"录音过程中发生错误: {e}")
        raise


if __name__ == "__main__":
    record_and_save()
